package array.leetcode.medium;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bruin_du
 * @description 和为 k 的子数组
 * @date 2022/8/3 18:09
 **/
public class OfferII010_SubarraySum {
    //前缀和加map优化
    //定义pre[i] 为 [0..i]里所有数的和
    //满足条件有pre[i]−pre[j−1]==k
    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        //将当前和等于k的情况放进去
        map.put(0, 1);
        int pro = 0, res = 0;
        for (int i = 0; i < nums.length; i++) {
            pro += nums[i];
            //满足pre[j−1] == pre[i]−k
            if (map.containsKey(pro - k)) {
                res += map.get(pro - k);
            }
            map.put(pro, map.getOrDefault(pro, 0) + 1);
        }
        return res;
    }
}
